package club.fuwenhao.netty;

import club.fuwenhao.bean.BaseMsg;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: fwh-netty
 * @description: 服务端处理类
 * @author: fwh
 * @date: 2021-10-28 12:53
 **/
@Slf4j
public abstract class BaseNettyServerHandler extends SimpleChannelInboundHandler<BaseMsg> {

    /**
     * 当客户端连接服务器完成就会触发该方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("本地地址为:{},远程地址为:{},上线成功", ctx.channel().localAddress(), ctx.channel().remoteAddress());
    }


    /**
     * 数据读取完毕处理方法
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer("HelloClient".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(buf);
    }

    /**
     * 接收客户端消息
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("从客户端读取到Object为:{}", JSON.toJSONString(msg));
    }
}
